<template>
    <a-modal
            title="新增供应商员工"
            :width="1024"
            :visible="visible"
            :confirmLoading="loading"
            @ok="handleSubmit"
            @cancel="() => { $emit('cancel') }"
    >
        <a-spin :spinning="loading" style="padding:15px 25px;">
<!--            <a-form :form="form" v-bind="formLayout">-->
<!--                <a-row class="form-row" :gutter="48">-->
<!--                    <div v-for="(v, k) in fields" :key="k">-->
<!--                        <a-col :lg="12" :md="12" :sm="24">-->
<!--                            <a-form-item :label="v.label">-->
<!--                                <template v-if="v.type == 'select'">-->
<!--                                    <a-select-->
<!--                                            v-decorator="[v.key, {initialValue:model?model[v.key]:'',rules: [{required: v.required,message: v.message}]}]"-->
<!--                                            @change="v.onChange">-->
<!--                                        <a-select-option :key="sk" v-for="(item,sk) in selectList[v.listName]" :value="v.listValue?item[v.listValue]:item">{{-->
<!--                                            item[v.listLabel] }}-->
<!--                                        </a-select-option>-->
<!--                                    </a-select>-->
<!--                                </template>-->
<!--                                <template v-else-if="v.type == 'password'">-->
<!--                                    <a-input-password v-decorator="[v.key, {initialValue:model?model[v.key]:'',rules: [{required: v.required,message: v.message}]}]" placeholder="請輸入密碼"/>-->
<!--                                </template>-->
<!--                                <template v-else-if="v.type == 'upload'">-->
<!--                                    <a-upload-->
<!--                                            name="file"-->
<!--                                            :showUploadList="false"-->
<!--                                            :customRequest="upload"-->
<!--                                    >-->
<!--                                        <a-button> <a-icon type="upload" /> Click to Upload </a-button>-->
<!--                                    </a-upload>-->
<!--                                    <span v-if="model!==null">{{ model[v.key] }}</span>-->
<!--                                </template>-->
<!--                                <template v-else-if="v.type == 'date'">-->
<!--                                    <a-date-picker valueFormat="yyyy-MM-DD" v-decorator="[v.key, {initialValue:model?model[v.key]:'',rules: [{required: v.required,message: v.message}]}]" />-->
<!--                                </template>-->
<!--                                <template v-else>-->
<!--                                    <a-input v-decorator="[v.key, {initialValue:model?model[v.key]:'',rules: [{required: v.required, min: 0, message: v.message, type: v.type?v.type:'string'}]}]"/>-->
<!--                                </template>-->
<!--                            </a-form-item>-->
<!--                        </a-col>-->
<!--                    </div>-->
<!--                </a-row>-->
<!--            </a-form>-->
          <a-table
                   :columns="columns"
                   :data-source="branchStorePurchaseOrderGoodsList"
                   class="components-table-demo-nested"
                   :pagination="false"
                   rowKey="idBraStoPurOrdGoo"
                   :expandedRowKeys="expandedRowKeys"
                   :defaultExpandAllRows="true"
          @expand="expand">
            <a slot="operation" slot-scope="text, record" @click="handleAdd(record)">分配倉庫</a>
            <a-table
              slot="expandedRowRender"
              slot-scope="text"
              :columns="innerColumns"
              :data-source="text.innerData"
              :pagination="false"
              :rowKey="(r, i) =>{ return i}"
            >
              <span slot="operation1" slot-scope="text,record,index" class="table-operation">
                <a @click="handleDelete(text,record,index)">刪除</a>
              </span>
            </a-table>
          </a-table>
          <warehouse-form
            ref="createModal"
            :visible="visibleWarehouse"
            :model="mdlWarehouse"
            :id-goo="idGoo"
            :id-bra-sto-pur-ord-goo="idBraStoPurOrdGoo"
            @ok="handleOk"
            @cancel="handleCancel"
          />
        </a-spin>
    </a-modal>
</template>

<script>
    import pick from 'lodash.pick'
    import { _getById, _dealBranchStorePurchaseOrder } from '@/api/BranchStorePurchaseOrder'
    import WarehouseForm from './PurchaseOrderGoodsFromWarehouse'
    // 表单字段
    const fields = [
        { key: 'idBraStoPurOrd', label: '', required: true, message: '' },
        { key: 'idBraSto', label: '', required: true, message: '' },
        { key: 'no', label: '', required: true, message: '' },
        { key: 'purchaseDate', label: '', required: true, message: '' },
        { key: 'type', label: '', required: true, message: '' },
        { key: 'status', label: '', required: true, message: '' }
    ]
    const columns = [
      { title: 'ID', dataIndex: 'idBraStoPurOrdGoo' },
      { title: '貨品編號', dataIndex: 'goodsNo' },
      { title: '貨品名稱', dataIndex: 'goodsNameHk' },
      { title: '訂購數量', dataIndex: 'quality' },
      { title: '單位', dataIndex: 'goodsUnit' },
      { title: '預設倉庫位置', dataIndex: 'defaultWarehouse' },
      { title: '預設倉庫存貨量', dataIndex: 'warehouseQuantity' },
      { title: '操作', key: 'operation', scopedSlots: { customRender: 'operation' } }
    ]

    const innerColumns = [
      { title: '倉庫名稱', dataIndex: 'warehouseName' },
      { title: '出貨量', dataIndex: 'subQuality' },
      {
        title: 'Action',
        dataIndex: 'operation',
        key: 'operation',
        scopedSlots: { customRender: 'operation1' }
      }
    ]

    export default {
        props: {
            visible: {
                type: Boolean,
                required: true
            },
            model: {
                type: Object,
                default: () => null
            }
        },
        components: {
          WarehouseForm
        },
        data () {
            this.formLayout = {
            }
            return {
                form: this.$form.createForm(this),
                fields: fields,
                loading: false,
                selectList: {
                },
                branchStorePurchaseOrder: {
                },
              branchStorePurchaseOrderGoodsList: [],
                columns,
                innerColumns,
              visibleWarehouse: false,
              mdlWarehouse: null,
              idGoo: 0,
              idBraStoPurOrdGoo: 0,
              expandedRowKeys: []
            }
        },
        created () {
            // 防止表单未注册
            fields.forEach((v, i) => this.form.getFieldDecorator(v.key))
            // 当 model 发生改变时，为表单设置值
            this.$watch('model', () => {
                this.model && this.form.setFieldsValue(pick(this.model, fields))
            })
            this.$watch('visible', (val) => {
              if (val) {
                _getById({
                  idBraStoPurOrd: this.model.idBraStoPurOrd
                }).then((ret) => {
                  this.branchStorePurchaseOrder = ret.data
                  // 初始化二級數組長度
                  for (let i = 0; i < this.branchStorePurchaseOrder.branchStorePurchaseOrderGoodsList.length; i++) {
                    this.branchStorePurchaseOrder.branchStorePurchaseOrderGoodsList[i]['innerData'] = []
                  }
                  this.branchStorePurchaseOrderGoodsList = this.branchStorePurchaseOrder.branchStorePurchaseOrderGoodsList
                  this.expandedRowKeys = []
                })
              }
            })
        },
        mounted () {
        },
        methods: {
            // handler
            handleSubmit (e) {
                e.preventDefault()
                this.$emit('handleRefresh')
                this.form.validateFields((err, values) => {
                    if (!err) {
                        // 新增
                        this.loading = true
                        const purchaseOrderGoodsFromWarehouseList = []
                      for (let i = 0; i < this.branchStorePurchaseOrder.branchStorePurchaseOrderGoodsList.length; i++) {
                        for (let j = 0; j < this.branchStorePurchaseOrder.branchStorePurchaseOrderGoodsList[i].innerData.length; j++) {
                          purchaseOrderGoodsFromWarehouseList.push(this.branchStorePurchaseOrder.branchStorePurchaseOrderGoodsList[i].innerData[j])
                        }
                      }
                      values['purchaseOrderGoodsListStr'] = JSON.stringify(this.data)
                      _dealBranchStorePurchaseOrder({
                        idBraStoPurOrd: this.model.idBraStoPurOrd,
                        purchaseOrderGoodsFromWarehouseListStr: JSON.stringify(purchaseOrderGoodsFromWarehouseList)
                      }).then((res) => this.handleSuccess(res))
                    }
                })
            },
            handleSuccess (ret) {
                this.loading = false
                if (ret.code === 0) {
                    this.form.resetFields()
                    this.$emit('cancel')
                    this.$message.info(ret.msg)
                } else {
                    this.$message.error('res.msg')
                }
            },
          handleAdd (record) {
            this.mdlWarehouse = null
            this.idGoo = record.idGoo
            this.idBraStoPurOrdGoo = record.idBraStoPurOrdGoo
            this.visibleWarehouse = true
          },
          handleDelete (text, record, index) {
            for (let i = 0; i < this.branchStorePurchaseOrderGoodsList.length; i++) {
              if (this.branchStorePurchaseOrderGoodsList[i].idBraStoPurOrdGoo === record.idBraStoPurOrdGoo) {
                this.branchStorePurchaseOrderGoodsList[i].innerData.splice(index, 1)
              }
            }
            var tempExpandedRowKeys = this.expandedRowKeys
            this.expandedRowKeys = []
            for (let i = 0; i < tempExpandedRowKeys.length; i++) {
              this.expandedRowKeys.push(tempExpandedRowKeys[i])
            }
          },
          handleOk (data) {
            // 解釋Goods對象並平鋪
            for (let i = 0; i < this.branchStorePurchaseOrder.branchStorePurchaseOrderGoodsList.length; i++) {
              if (this.branchStorePurchaseOrder.branchStorePurchaseOrderGoodsList[i].idBraStoPurOrdGoo === data.idBraStoPurOrdGoo) {
                this.branchStorePurchaseOrder.branchStorePurchaseOrderGoodsList[i].innerData.push(data)
              }
            }
            this.visibleWarehouse = false
            // const form = this.$refs.createModal.form
            // form.resetFields() // 清理表单数据（可不做）
            // this.$refs.table.refresh() // 刷新表格
            // this.$refs.bbb.updateColumns() // 刷新表格
            var tempExpandedRowKeys = this.expandedRowKeys
            this.expandedRowKeys = []
            for (let i = 0; i < tempExpandedRowKeys.length; i++) {
              this.expandedRowKeys.push(tempExpandedRowKeys[i])
            }
          },
          handleCancel () {
            this.visibleWarehouse = false
          },
          expand (expanded, record) {
              if (!expanded) {
                for (var i = 0; i < this.expandedRowKeys.length; i++) {
                  if (this.expandedRowKeys[i] === record.idBraStoPurOrdGoo) {
                    this.expandedRowKeys.splice(i, 1)
                  }
                }
              } else {
                this.expandedRowKeys.push(record.idBraStoPurOrdGoo)
              }
          }
        }
    }
</script>
